﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using KorbeRTR.Models;

namespace KorbeRTR
{
    public partial class FormFloatBoardPositionSet : Form
    {
        public FormFloatBoardPositionSet()
        {
            InitializeComponent();
        }

        private void FormFloatBoardPositionSet_Load(object sender, EventArgs e)
        {
            InitGrid(grid浮板高度);

            UpdateGrid(grid浮板高度);
        }
        private void InitGrid(FlexCell.Grid grid)
        {
            grid.AutoRedraw = false;

            var dict = FBGD.ListAll();

            grid.Rows = dict.Count + 1;
            grid.Cols = 2;
            grid.Column(0).Width = (short)(grid.Width / 3);
            grid.Column(1).Width = (short)(grid.Width / 2);

            //这个包围区间要减1
            grid.Range(0, 0, grid.Rows - 1, grid.Cols - 1).Alignment = FlexCell.AlignmentEnum.CenterCenter;
            int col = 0;     
            grid.Cell(0, col++).Text = "浮板高度(mm)";
            grid.Cell(0, col++).Text = "位置(mm)";


            grid.AutoRedraw = true;
            grid.Refresh();
        }

        private void UpdateGrid(FlexCell.Grid grid)
        {
            grid.AutoRedraw = false;

            var dict = FBGD.ListAll();
            grid.Rows = dict.Count + 1;
            int row = 1;
            foreach (var iter in dict.Values)
            {
                grid.Cell(row, 0).Text = iter.板高.ToString();
                grid.Cell(row, 1).Text = iter.位置.ToString();
                row++;
            }

            grid.AutoRedraw = true;
            grid.Refresh();
        }

        private void btn退出_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btn应用_Click(object sender, EventArgs e)
        {
            var dict = FBGD.ListAll();
            for(int row=1; row<grid浮板高度.Rows; row++)
            {
                int bg = int.Parse(grid浮板高度.Cell(row, 0).Text);
                int wz = int.Parse(grid浮板高度.Cell(row, 1).Text);
                dict[bg].位置 = wz;
            }

            using (var conn = KorbeRTR.Utility.FBGDDBHelper.Open())
            {
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        foreach(var iter in dict.Values)
                        {
                            var a = FBGD.Update(trans, iter);
                            Console.WriteLine(a);
                        }
                        trans.Commit();
                    }
                    catch(Exception err)
                    {
                        trans.Rollback();
                        throw err;
                    }
                }
            }
        }
    }
}
